package com.car.slave.im.util;

import java.io.Closeable;
import java.io.IOException;

import android.content.Context;

import com.car.slave.im.model.user.IMAudioMessage;
import com.car.slave.im.model.user.IMImageMessage;
import com.car.slave.im.util.QiuniuUtil.UploadFileCallback;

public class IMTool {
	
	public static byte[] getIoBuffer(int code, String content) {
		byte[] buf = content.getBytes();
		int len = buf.length + 6;
		byte[] conBuffer = new byte[len];
		// 长度
        System.arraycopy(intToBuffer(len), 0, conBuffer, 0, 2);
        // version
        System.arraycopy(intToBuffer(code), 0, conBuffer, 2, 2);
        // code
        System.arraycopy(intToBuffer(code), 0, conBuffer, 4, 2);
        // 内容
        System.arraycopy(buf, 0, conBuffer, 6, buf.length);
        return conBuffer;
	}

	public static int bufferToInt(byte[] b) {
		/*
	    int iOutcome = 0;
	    byte bLoop;
	    for (int i = 0; i < buffer.length; i++) {
	        bLoop = buffer[i];
	        iOutcome += (bLoop & 0xFF) << (8 * i);
	    }
	    return iOutcome;
	    */
		int s = 0 ;  
		if (b[0] >= 0) {  
			s = s + b[0];  
		} else {  
			s = s + 256 + b[0];  
		}  
		s = s * 256 ;  
		if (b[1] >= 0) {  
			s = s + b[1];  
		} else {  
			s = s + 256 + b[1];  
		}  
		short result = (short)s;  
		return result;  
	}
	
	/**
	 * 整形转成2个字节数组.
	 * @param i
	 * @return
	 */
	public static byte[] intToBuffer(int i) {
		byte[] buf = new byte[2];  
//        buf[0] = (byte) (i & 0xFF);  
//        buf[1] = (byte) (i >> 8 & 0xFF);
		 buf[1] = (byte) (i & 0xFF);  
		 buf[0] = (byte) (i >> 8 & 0xFF);
        return buf;
	}
	
	/**
	 * 关闭流.
	 * @param closeable
	 */
	public static void closeStream(Closeable closeable) {
		if (null != closeable) {
			try {
				closeable.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 上传图片.
	 * @param message
	 * @return 上传后的网络路径.
	 */
	public static void uploadImage(Context context, IMImageMessage message, UploadFileCallback ufCallback) {
		QiuniuUtil upFile = new QiuniuUtil(context, message.imageFilePath, ufCallback);
		upFile.upload();
	}
	
	/**
	 * 上传声音.
	 * @param message
	 * @return	上传后的网络路径.
	 */
	public static void uploadAudio(Context context,IMAudioMessage message, UploadFileCallback ufCallback) {
		QiuniuUtil upFile = new QiuniuUtil(context, message.audioFilePath, ufCallback);
		upFile.upload();
	}
}
